<template>
    <div style="background-color: #FFF7E1; min-height: 100vh; padding-bottom: 60px;">
        <!-- 导航栏 -->
        <van-nav-bar title="食谱详情" style="background-color: #FFD85F;" left-arrow @click-left="goBack" />

        <!-- 食谱详情内容 -->
        <div class="recipe-details">
            <van-image class="recipe-image" :src="recipe.imageUrl" width="100%" height="200" fit="cover" />

            <!-- 食谱基本信息 -->
            <div class="recipe-info">
                <h2>{{ recipe.recipeName }}</h2>
                <p><strong>类别：</strong> {{ recipe.category }}</p>
                <p><strong>卡路里：</strong> {{ recipe.calories }} kcal</p>
                <p><strong>蛋白质：</strong> {{ recipe.protein }} g</p>
                <p><strong>脂肪：</strong> {{ recipe.fat }} g</p>
                <p><strong>碳水化合物：</strong> {{ recipe.carbohydrate }} g</p>
            </div>

            <!-- 食谱描述 -->
            <div class="recipe-description">
                <h3>食谱描述</h3>
                <p>{{ recipe.description }}</p>
            </div>

            <!-- 制作步骤 -->
            <div class="recipe-instructions">
                <h3>制作步骤</h3>
                <span>
                    {{ recipe.instructions }}
                </span>
            </div>

            <!-- 用户评论 -->
            <div class="comments-section">
                <h3>用户评论</h3>
                <div class="comment-list">
                    <div v-for="(comment, index) in comments" :key="index" class="comment-item">
                        <div class="comment-header">
                            <img :src="comment.avatar" alt="用户头像" class="avatar" />
                            <span class="username">{{ comment.username }}</span>
                        </div>
                        <p class="comment-text">{{ comment.text }}</p>
                        <!-- 只允许当前用户删除自己的评论 -->
                        <div class="comment-actions" v-if="comment.userId === currentUserId">
                            <van-button type="danger" size="mini" @click="deleteComment(comment.id)">删除</van-button>
                        </div>
                        <hr />
                    </div>
                </div>

                <!-- 添加评论 -->
                <div class="add-comment">
                    <van-field v-model="newComment" placeholder="添加一条评论" type="textarea" rows="2" autosize />
                    <van-button type="primary" block @click="addComment">提交评论</van-button>
                </div>
            </div>
        </div>

        <!-- 固定底部操作栏 -->
        <div class="fixed-bottom-bar">
            <div class="action-item" @click="toggleLike">
                <van-icon :name="isLiked ? 'like' : 'like-o'" :color="isLiked ? 'red' : 'gray'" size="24" />
                <span>{{ isLiked ? '已点赞' : '点赞' }} {{ likesCount }}</span>
            </div>
            <div class="action-item" @click="addToFavorites">
                <van-icon :name="isStar ? 'star' : 'star-o'" :color="isStar ? 'red' : 'gray'" size="24" />
                <span>{{ isStar ? '已收藏' : '收藏' }}</span>
            </div>
        </div>
    </div>
</template>

<script>
import axios from 'axios';
import { NavBar, Image as VanImage, Button, Field, Icon } from 'vant';

export default {
    components: {
        [NavBar.name]: NavBar,
        [VanImage.name]: VanImage,
        [Button.name]: Button,
        [Field.name]: Field,
        [Icon.name]: Icon,
    },
    data() {
        return {
            recipe: [],

            currentUserId: null, // 当前用户 ID 判断删除按钮是否显示
            comments: [],//评论列表
            newComment: '',
            isLiked: false, // 是否已点赞,
            isStar: false,//是否已收藏
            likesCount: 0, // 点赞数
        };
    },
    methods: {
        goBack() {
            this.$router.back();
        },
        addToFavorites() {
            const token = localStorage.getItem('token'); // 从 localStorage 获取 token
            if (!token) {
                Toast.fail('请先登录！');
                return;
            }
            axios({
                method: 'POST',
                url: `http://localhost:8081/wx/favorites/toggle?recipeId=${this.recipe.id}`,
                headers: {
                    token: token
                }
            }).then(res => {
                if (res.data.errno === 0) {
                    this.isStar = !this.isStar;


                } else {
                    Toast.fail('操作失败，请稍后再试！');
                }
            }).catch(() => {
                Toast.fail('网络错误，请稍后再试！');
            })

        },

        toggleLike() {

            const token = localStorage.getItem('token'); // 从 localStorage 获取 token
            if (!token) {
                Toast.fail('请先登录！');
                return;
            }
            axios({

                method: 'POST',
                url: `http://localhost:8081/wx/like/toggle?recipeId=${this.recipe.id}`,
                headers: {
                    token: token
                }
            })
                .then(res => {

                    if (res.data.errno === 0) {
                        this.isLiked = !this.isLiked;
                        this.likesCount += this.isLiked ? 1 : -1;
                    } else {
                        Toast.fail('操作失败，请稍后再试！');
                    }
                })
                .catch(() => {
                    Toast.fail('网络错误，请稍后再试！');
                });



        },

        likeRecipe() {
            this.likes += 1;
        },
        addComment() {
            if (this.newComment.trim() === '') {
                alert('评论不能为空！');
                return;
            }
            const token = localStorage.getItem('token'); // 获取 Token
            if (!token) {
                this.$toast.fail('请先登录！');
                return;
            }

            axios({
                method: 'POST',
                url: `http://localhost:8081/wx/comments/add?recipeId=${this.recipe.id}&content=${this.newComment}`,
                headers: { token }
            })
                .then(res => {
                    console.log(res)
                    if (res.data.errno === 0) {
                        this.$toast.success('评论成功');
                        this.newComment = '';
                        this.fetchComments(); // 重新获取评论列表
                    } else {
                        this.$toast.fail(res.data.message);
                    }
                })
                .catch(() => {
                    this.$toast.fail('网络错误，请稍后再试！');
                });



        },
        deleteComment(id) {

            const token = localStorage.getItem('token');
            if (!token) {
                this.$toast.fail('请先登录！');
                return;
            }
            axios({
                method: 'DELETE',
                url: `http://localhost:8081/wx/comments/delete?commentId=${id}`,
                headers: { token }
            }).then(res => {

                if (res.data) {
                    this.$toast.success('删除成功');
                    this.fetchComments(); // 重新获取评论列表
                } else {
                    this.$toast.fail('删除失败，请稍后再试！');
                }
            }).catch(() => {
                this.$toast.fail('网络错误，请稍后再试！');
            });
        },
        fetchComments() {
            const recipeId = this.$route.params.id;
            axios.get(`http://localhost:8081/wx/comments/list?recipeId=${recipeId}`)
                .then(res => {


                    this.comments = res.data.data.map(comment => ({

                        avatar: comment.avatar || 'https://i.pravatar.cc/50',
                        username: comment.username,
                        text: comment.content,
                        id: comment.id,
                        userId: comment.userId, // 新增：记录用户 ID
                    }));
                });
        }
    },
    created() {
        const recipeId = this.$route.params.id;

        const token = localStorage.getItem('token');
        axios({
            url: "http://localhost:8081/wx/recipes/id?id=" + this.$route.params.id
        }).then(res => {

            this.recipe = res.data.data
            this.likesCount = res.data.data.likesCount;
        })
        // 获取点赞状态
        axios.get(`http://localhost:8081/wx/like/status?recipeId=${recipeId}`, {
            headers: { token: token }
        }).then(res => {

            this.isLiked = res.data.data.liked;
        });

        //获取收藏状态
        axios.get(`http://localhost:8081/wx/favorites/status?recipeId=${recipeId}`, {
            headers: { token: token }
        }).then(res => {

            if (res.data.data.liked === 1) {
                this.isStar = true
            } else {
                this.isStar = false
            }
        });
        // 获取评论列表
        this.fetchComments();
        // 获取当前登录用户自己的评论（用来判断当前用户 ID）
        axios.get('http://localhost:8081/wx/admin/commect/list', {
            headers: { token }
        }).then(res => {
            if (res.data.errno === 0 && res.data.data.length > 0) {
                this.currentUserId = res.data.data[0].userId; // 假设用户的 userId 是固定的
            }
        });

    }
};
</script>

<style scoped>
.comment-actions {
    text-align: right;
    margin-top: -40px;
}

.recipe-details {
    padding: 20px;
}

.recipe-image {
    border-radius: 10px;
    margin-bottom: 20px;
}

.recipe-info h2 {
    color: #D89A38;
    font-size: 1.6em;
    font-weight: bold;
    margin-bottom: 10px;
}

.recipe-info p {
    font-size: 1em;
    color: #4B3F30;
    margin: 5px 0;
}

.recipe-description,
.recipe-instructions,
.comments-section {
    margin-top: 20px;
    padding: 15px;
    background-color: #FFE7B2;
    border-radius: 8px;
}

.recipe-description h3,
.recipe-instructions h3,
.comments-section h3 {
    font-size: 1.2em;
    color: #D89A38;
    margin-bottom: 10px;
}

.comment-list {
    margin-top: 15px;
}

.comment-item {
    margin-bottom: 15px;
}

.comment-header {
    display: flex;
    align-items: center;
    margin-bottom: 5px;
}

.avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    margin-right: 10px;
}

.username {
    font-size: 1em;
    font-weight: bold;
    color: #4B3F30;
}

.comment-text {
    font-size: 0.95em;
    color: #4B3F30;
}

hr {
    border: none;
    border-top: 1px solid #D89A38;
    margin: 10px 0;
}

.add-comment {
    margin-top: 15px;
}

/* 固定底部操作栏 */
.fixed-bottom-bar {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    background-color: #FFD85F;
    display: flex;
    justify-content: space-around;
    align-items: center;
    padding: 10px 0;
    box-shadow: 0 -2px 5px rgba(0, 0, 0, 0.1);
    z-index: 1000;
}

.action-item {
    text-align: center;
    color: #4B3F30;
    font-size: 14px;
    cursor: pointer;
}

.action-item span {
    margin-top: 5px;
    display: block;
}
</style>
